/**
 * tools util
 */

import consts from './consts';
var uuidHelper = require("./UuidHelper");

var tool = {
    INIT_STYLE_TIME: 0,
    addTween: function(pw, we, an, start_time, end_time, type, tween, pathProvider, centerOffsetToBorderOffsetByEditorCanvas, scale) {
        this.INIT_STYLE_TIME = 0.001;
        var widgetScope = we;
        we = $(we.elements.widget);
        //       we = $(we);
        start_time = parseFloat(start_time == -1 ? 0 : start_time);
        end_time = parseFloat(end_time);
        // 新增传入参数（画布大小），解决画布缩放预览动效错位问题
        var scale = scale || 1;
        var duration = end_time - start_time,
            start_css_style,
            end_css_style;
        tween = parseInt(tween);

        var that = this;

        var an_type = consts.AN_TYPE;
        var an_direction = consts.AN_DIRECTION;

        // 无动画时不作处理
        if (an.an_type != an_type.ANIMATION_NONE) {
            pw.insert(
                TweenMax.to(
                    we,
                    this.INIT_STYLE_TIME, {
                        css: {
                            'opacity': 0
                        },
                        ease: Quart.easeIn
                    }
                ),
                0
            );
        }

        switch (tween) {
            case 0:
                tween = Linear.easeNone;
                if (an.an_type == an_type.BOUNCE) tween = Bounce.easeOut;
                break;
            case 1:
                tween = Quart.easeOut;
                if (an.an_type == an_type.BOUNCE) tween = Bounce.easeOut;
                break;
            case 2:
                tween = Quart.easeIn;
                if (an.an_type == an_type.BOUNCE) tween = Bounce.easeOut;
            break;
        }
        switch (an.an_type) {
            // 淡入
            case an_type.FADE_IN:
                we.data('has_fade_in_tween', true);
                pw.insert(
                    TweenMax.to(
                        we,
                        this.INIT_STYLE_TIME, {
                            css: {
                                'opacity': 0
                            },
                            ease: tween
                        }
                    ),
                    start_time
                );
                pw.insert(
                    TweenMax.to(
                        we,
                        duration, {
                            css: {
                                'opacity': 1
                            },
                            ease: tween
                        }
                    ),
                    start_time + this.INIT_STYLE_TIME
                );
                break;
                // 擦出
            case an_type.ERASE:
                we.data('has_erase_tween', true);
                var wi = we.find('.render-widget');
                // direction
                var direction = parseInt(an.direction || an_direction.TOP_TO_BOTTOM);
                switch (direction) {
                    case an_direction.TOP_TO_BOTTOM:
                        start_css_style = {
                            clip: "rect(0px " + wi.width() + "px " + "0px " + "0px)"
                        };
                        end_css_style = {
                            clip: "rect(0px " + wi.width() + "px " + wi.height() + "px " + "0px)"
                        };
                        break;
                    case an_direction.BOTTOM_TO_UP:
                        start_css_style = {
                            clip: "rect(" + wi.height() + "px " + wi.width() + "px " + wi.height() + "px " + "0px)"
                        };
                        end_css_style = {
                            clip: "rect(0px " + wi.width() + "px " + wi.height() + "px " + "0px)"
                        };
                        break;
                    case an_direction.LEFT_TO_RIGHT:
                        start_css_style = {
                            clip: "rect(0px " + "0px " + wi.height() + "px " + "0px)"
                        };
                        end_css_style = {
                            clip: "rect(0px " + wi.width() + "px " + wi.height() + "px " + "0px)"
                        };
                        break;
                    case an_direction.RIGHT_TO_LEFT:
                        start_css_style = {
                            clip: "rect(0px " + wi.width() + "px " + wi.height() + "px " + wi.width() + "px)"
                        };
                        end_css_style = {
                            clip: "rect(0px " + wi.width() + "px " + wi.height() + "px " + "0px)"
                        };
                        break;
                }
                pw.insert(
                    TweenMax.to(
                        wi,
                        this.INIT_STYLE_TIME,
                        $.extend(
                            $.extend(start_css_style, {
                                position: 'absolute'
                            }), {
                                ease: tween
                            })
                    ),
                    start_time
                );
                var init_style = {};
                if (!we.data('has_fade_in_tween') && !we.data('has_flicker_tween')) {
                    pw.insert(
                        TweenMax.to(
                            we,
                            this.INIT_STYLE_TIME, {
                                css: {
                                    opacity: 1
                                },
                                ease: tween,
                            }
                        ),
                        start_time + this.INIT_STYLE_TIME
                    );
                }
                pw.insert(
                    TweenMax.to(
                        wi,
                        duration,
                        $.extend(end_css_style, {
                            ease: tween,
                            onComplete: function() {
                                wi.removeAttr('style');
                                we.css({
                                    overflow: 'visible'
                                })
                            }
                        })
                    ),
                    start_time + this.INIT_STYLE_TIME
                );
                break;
                // 飞入
            case an_type.FLY_INTO:
                we.data('has_fly_into_tween', true);
                // 某些情况下h5页面无法获取到位置
                var width = we.width(),
                    height = we.height(),
                    left = we.position().left || parseFloat($(we).css('left')),
                    top = we.position().top || parseFloat($(we).css('top')),
                    // direction
                    direction = parseInt(an.direction || an_direction.TOP_TO_BOTTOM);
                switch (direction) {
                    case an_direction.TOP_TO_BOTTOM:
                        start_css_style = {
                            top: (top - 5 * height) / scale,
                            scale: 0,
                        };
                        end_css_style = {
                            top: top / scale,
                            opacity: 1,
                            scale: 1
                        };
                        break;
                    case an_direction.BOTTOM_TO_UP:
                        start_css_style = {
                            top: (top + 5 * height) / scale,
                            scale: 0
                        };
                        end_css_style = {
                            top: top,
                            opacity: 1,
                            scale: 1
                        };
                        break;
                    case an_direction.LEFT_TO_RIGHT:
                        start_css_style = {
                            left: (left - 5 * width) / scale,
                            scale: 0
                        };
                        end_css_style = {
                            left: (left) / scale,
                            opacity: 1,
                            scale: 1
                        };
                        break;
                    case an_direction.RIGHT_TO_LEFT:
                        start_css_style = {
                            left: (left + 5 * width) / scale,
                            scale: 0
                        };
                        end_css_style = {
                            left: left / scale,
                            opacity: 1,
                            scale: 1
                        };
                        break;
                }
                pw.insert(
                    TweenMax.to(
                        we,
                        this.INIT_STYLE_TIME,
                        $.extend(
                            start_css_style, {
                                ease: tween
                            }
                        )
                    ),
                    start_time
                );
                var init_style = {

                };
                if (!we.data('has_fade_in_tween') && !we.data('has_flicker_tween')) {
                    pw.insert(
                        TweenMax.to(
                            we,
                            this.INIT_STYLE_TIME, {
                                css: {
                                    opacity: 1,
                                    'overflow': 'hidden'
                                },
                                ease: tween,
                            }
                        ),
                        start_time + this.INIT_STYLE_TIME
                    );
                }

                pw.insert(
                    TweenMax.to(
                        we,
                        duration,
                        $.extend(end_css_style, {
                            ease: tween,
                            onComplete: function() {
                                we.css({
                                    overflow: 'visible'
                                })
                            }
                        })
                    ),
                    start_time + this.INIT_STYLE_TIME
                );
                break;
                // 切入
            case an_type.CUT:
                we.data('has_cut_tween', true);
                // 某些情况下h5页面无法获取到宽 高 和 位置 anti-moth
                var wi = we.find('.render-widget'),
                    width = wi.width() || wi.find('img').width() || we.width(),
                    height = wi.height() || wi.find('img').height() || we.height(),
                    left = wi.position() ? wi.position().left : 0,
                    top = wi.position() ? wi.position().top : 0,

                    // direction
                    direction = parseInt(an.direction || an_direction.TOP_TO_BOTTOM);
                switch (direction) {
                    case an_direction.TOP_TO_BOTTOM:
                        start_css_style = {
                            top: top - height
                        };
                        end_css_style = {
                            top: top,
                            opacity: 1,
                        };
                        break;
                    case an_direction.BOTTOM_TO_UP:
                        start_css_style = {
                            top: top + height
                        };
                        end_css_style = {
                            top: top,
                            opacity: 1,
                        };
                        break;
                    case an_direction.LEFT_TO_RIGHT:
                        start_css_style = {
                            left: left - width
                        };
                        end_css_style = {
                            left: left,
                            opacity: 1,
                        };
                        break;
                    case an_direction.RIGHT_TO_LEFT:
                        start_css_style = {
                            left: left + width
                        };
                        end_css_style = {
                            left: left,
                            opacity: 1,
                        };
                        break;
                }
                start_css_style = $.extend(start_css_style, {
                    'max-width': 'none',
                    'max-height': '100%',
                    'position': 'absolute'
                });
                pw.insert(
                    TweenMax.to(
                        wi,
                        this.INIT_STYLE_TIME,
                        $.extend(
                            start_css_style, {
                                ease: tween
                            }
                        )
                    ),
                    start_time
                );
                var init_style = {
                    'overflow': 'hidden'
                };
                if (!we.data('has_fade_in_tween') && !we.data('has_flicker_tween')) {
                    pw.insert(
                        TweenMax.to(
                            we,
                            this.INIT_STYLE_TIME, {
                                css: {
                                    opacity: 1,
                                    'overflow': 'hidden'
                                },
                                ease: tween
                            }
                        ),
                        start_time + this.INIT_STYLE_TIME
                    );
                }
                pw.insert(
                    TweenMax.to(
                        wi,
                        duration,
                        $.extend(end_css_style, {
                            ease: tween,
                            onComplete: function() {
                                wi.removeAttr('style');
                                we.css({
                                    overflow: 'visible'
                                });
                            }
                        })
                    ),
                    start_time + this.INIT_STYLE_TIME
                );
                break;
                // 闪烁 / 透明度
            case an_type.FLICKER:
                we.data('has_flicker_tween', true);
                var loop = this.parse_loop(an, duration),
                    start_value = parseFloat(an.start_value),
                    end_value = parseFloat(an.end_value);
                if (!loop.type) {
                    // start not repeat
                    pw.insert(
                        TweenMax.to(
                            we,
                            this.INIT_STYLE_TIME, {
                                opacity: parseFloat(start_value)
                            }
                        ),
                        start_time
                    );
                    pw.insert(
                        TweenMax.to(
                            we,
                            duration, {
                                opacity: parseFloat(end_value),
                                ease: tween,
                                onComplete: function() {

                                }
                            }
                        ),
                        start_time + this.INIT_STYLE_TIME
                    );
                    // end not repeat
                } else {
                    // start if repeat
                    we.removeClass('btg-widget-in-animation');
                    pw.insert(
                        TweenMax.to(
                            we,
                            this.INIT_STYLE_TIME, {
                                opacity: parseFloat(start_value)
                            }
                        ),
                        start_time
                    );
                    pw.insert(
                        TweenMax.to(
                            we,
                            loop.duration, {
                                opacity: parseFloat(end_value),
                                repeat: loop.repeat,
                                yoyo: loop.yoyo,
                                ease: tween,
                                onComplete: function() {
                                    we.css({
                                        'opacity': '1'
                                    });
                                }
                            }
                        ),
                        start_time + this.INIT_STYLE_TIME
                    );
                }
                break;
                // 弹跳
            case an_type.BOUNCE:
                we.data('has_bounce_tween', true);
                var wi = we.find('.render-widget');
                // 某些情况下h5页面无法获取到位置
                var width = we.width(),
                    height = we.height(),
                    left = we.position().left || parseFloat($(we).css('left')),
                    top = we.position().top || parseFloat($(we).css('top')),
                    // direction
                    direction = parseInt(an.direction || an_direction.TOP_TO_BOTTOM);
                if (isNaN(top)) top = 0;
                if (isNaN(left)) left = 0;
                switch (direction) {
                    case an_direction.TOP_TO_BOTTOM:
                        start_css_style = {
                            top: (top - 3 * height) / scale
                        };
                        end_css_style = {
                            top: top / scale,
                        };
                        break;
                    case an_direction.BOTTOM_TO_UP:
                        start_css_style = {
                            top: (top + 3 * height) / scale
                        };
                        end_css_style = {
                            top: top / scale,
                        };
                        break;
                    case an_direction.LEFT_TO_RIGHT:
                        start_css_style = {
                            left: (left - 3 * width) / scale
                        };
                        end_css_style = {
                            left: left / scale,
                        };
                        break;
                    case an_direction.RIGHT_TO_LEFT:
                        start_css_style = {
                            left: (left + 3 * width) / scale
                        };
                        end_css_style = {
                            left: left / scale,
                        };
                        break;
                }
                pw.insert(
                    TweenMax.to(
                        we,
                        this.INIT_STYLE_TIME,
                        $.extend(
                            start_css_style, {
                                ease: tween,
                            }
                        )
                    ),
                    start_time
                );
                var init_style = {

                };
                if (!we.data('has_fade_in_tween') && !we.data('has_flicker_tween')) {
                    pw.insert(
                        TweenMax.to(
                            we,
                            this.INIT_STYLE_TIME, {
                                css: {
                                    opacity: 1
                                },
                                ease: tween,
                            }
                        ),
                        //                    start_time
                        start_time + this.INIT_STYLE_TIME
                    );
                }

                pw.insert(
                    TweenMax.to(
                        we,
                        duration,
                        $.extend(end_css_style, {
                            ease: tween,
                            onComplete: function() {
                                we.css({
                                    overflow: 'visible'
                                });
                            }
                        })
                    ),
                    start_time + this.INIT_STYLE_TIME
                );
                break;
                // 淡出
            case an_type.FADE_OUT:
                we.data('has_fade_out_tween', true);
                pw.insert(
                    TweenMax.to(
                        we,
                        this.INIT_STYLE_TIME, {
                            css: {
                                'opacity': 1
                            },
                            ease: tween
                        }
                    ),
                    start_time + this.INIT_STYLE_TIME

                );
                pw.insert(
                    TweenMax.to(
                        we,
                        duration, {
                            css: {
                                'opacity': 0
                            },
                            ease: tween
                        }
                    ),
                    start_time + this.INIT_STYLE_TIME
                );
                break;
                // 缩放
            case an_type.ZOOM:
            case an_type.ZOOMOUT:
                we.data('has_zoom_tween', true);
                var loop = this.parse_loop(an, duration),
                    start_value = parseFloat(an.start_value || 0),
                    end_value = parseFloat(an.end_value);
                if (!loop.type) {
                    if (!we.data('has_fade_in_tween') && !we.data('has_flicker_tween')) {
                        pw.insert(
                            TweenMax.to(
                                we,
                                this.INIT_STYLE_TIME, {
                                    css: {
                                        opacity: 1
                                    },
                                    ease: tween,
                                }
                            ),
                            start_time + this.INIT_STYLE_TIME
                        );
                    }
                    pw.insert(
                        TweenMax.to(
                            we,
                            this.INIT_STYLE_TIME, {
                                scale: parseFloat(start_value),
                            }
                        ),
                        start_time
                    );
                    pw.insert(
                        TweenMax.to(
                            we,
                            duration, {
                                scale: parseFloat(end_value),
                                ease: tween,
                                onComplete: function() {

                                }
                            }
                        ),
                        start_time
                    );
                } else {
                    start_css_style = {
                        opacity: parseFloat(start_value),
                    };
                    end_css_style = {
                        opacity: parseFloat(end_value),
                    }

                    we.removeClass('btg-widget-in-animation');
                    if (!we.data('has_fade_in_tween') && !we.data('has_flicker_tween')) {
                        pw.insert(
                            TweenMax.to(
                                we,
                                this.INIT_STYLE_TIME, {
                                    css: {
                                        opacity: 1
                                    },
                                    ease: tween,
                                }
                            ),
                            start_time + this.INIT_STYLE_TIME
                        );
                    }
                    pw.insert(
                        TweenMax.to(
                            we,
                            this.INIT_STYLE_TIME, {
                                scale: parseFloat(start_value),
                            }
                        ),
                        start_time
                    );
                    pw.insert(
                        TweenMax.to(
                            we,
                            loop.duration, {
                                scale: parseFloat(end_value),
                                repeat: loop.repeat,
                                yoyo: loop.yoyo,
                                ease: tween,
                                onComplete: function() {
                                    we.css({
                                        '-webkit-transform': 'scale(1)'
                                    });
                                }
                            }
                        ),
                        start_time
                    );
                }
                break;
                // 呼吸灯
            case an_type.BREATHING_LIGHT:
                we.data('has_breathing_light_tween', true);
                var if_repeat = an.if_repeat,
                    single_speed = an.single_speed,
                    color = an.color,
                    repeat, target;
                var rgbColor = is.hexToRgb(color);
                var rgbaStart = 'rgba(' + rgbColor.r + ',' + rgbColor.g + ',' + rgbColor.b + ',0)';
                var rgbaEnd = 'rgba(' + rgbColor.r + ',' + rgbColor.g + ',' + rgbColor.b + ',0.7)';
                if (type == 'custom') {
                    target = we;
                } else {
                    target = we.find('.widget');
                }
                if (!if_repeat) {
                    pw.insert(
                        TweenMax.fromTo(target, duration, {
                            boxShadow: "0px 0px 10px 10px " + rgbaStart
                        }, {
                            boxShadow: "0px 0px 10px 10px " + rgbaEnd,
                            ease: tween,
                            onComplete: function() {
                                target.css({
                                    'box-shadow': 'none'
                                });
                            }
                        }),
                        start_time
                    );
                } else {
                    single_speed = parseFloat(single_speed) / 2;
                    repeat = duration / single_speed;
                    duration = single_speed;
                    pw.insert(
                        TweenMax.fromTo(target, duration, {
                            boxShadow: "0px 0px 10px 10px " + rgbaStart
                        }, {
                            boxShadow: "0px 0px 10px 10px " + rgbaEnd,
                            repeat: repeat,
                            yoyo: true,
                            ease: tween,
                            onComplete: function() {
                                target.css({
                                    'box-shadow': 'none'
                                });
                            }
                        }),
                        start_time
                    );
                }
                break;
                // 旋转
            case an_type.ROTATE:
                we.data('has_rotate_tween', true);
                var wi = we.find('.render-widget');
                var loop = this.parse_loop(an, duration),
                    start_value = parseFloat(an.start_value || 0),
                    end_value = parseFloat(an.end_value == undefined ? (duration ? 360 : -360) : an.end_value);
                // 修改旋转动画设置从-角度到+角度时实际效果不对
                end_value = end_value - start_value;

                if (!we.data('has_fade_in_tween') && !we.data('has_flicker_tween')) {
                    pw.insert(
                        TweenMax.to(
                            we,
                            this.INIT_STYLE_TIME, {
                                css: {
                                    opacity: 1
                                },
                                ease: tween,
                            }
                        ),
                        start_time + this.INIT_STYLE_TIME
                    );
                }

                if (!loop.type) {
                    var init_style = {
                        rotationZ: start_value,
                    };
                    pw.insert(
                        TweenMax.to(
                            we,
                            this.INIT_STYLE_TIME, {
                                css: init_style,
                                ease: tween,
                            }
                        ),
                        start_time
                    );
                    pw.insert(
                        TweenMax.to(
                            we, duration, {
                                rotationZ: end_value,
                                ease: tween,
                                onComplete: function() {
                                    wi.removeAttr('style');
                                    if (widgetScope.widget.rotate_z) {
                                        wi.css({
                                            '-webkit-transform': 'rotateZ(' + widgetScope.widget.rotate_z + 'deg)',
                                        });
                                    };
                                }
                            }),
                        start_time
                    );
                } else {
                    var init_style = {
                        rotationZ: start_value,
                    };
                    pw.insert(
                        TweenMax.to(
                            we,
                            this.INIT_STYLE_TIME, {
                                css: init_style,
                                ease: tween,
                            }
                        ),
                        start_time
                    );
                    pw.insert(
                        TweenMax.to(
                            we, loop.duration, {
                                rotationZ: end_value,
                                repeat: loop.repeat,
                                yoyo: loop.yoyo,
                                ease: tween,
                                onComplete: function() {
                                    wi.removeAttr('style');
                                    if (widgetScope.widget.rotate_z) {
                                        wi.css({
                                            '-webkit-transform': 'rotateZ(' + widgetScope.widget.rotate_z + 'deg)',
                                        });
                                    };
                                }
                            }),
                        start_time
                    );
                }
                break;
                // 翻转
            case an_type.TRUN:
                we.data('has_trun_tween', true);
                var wi = we.find('.render-widget'),
                    startRotateX = an.start_rotate_x,
                    startRotateY = an.start_rotate_y,
                    startRotateZ = an.start_rotate_z,
                    endRotateX = an.end_rotate_x,
                    endRotateY = an.end_rotate_y,
                    endRotateZ = an.end_rotate_z;
                var loop = this.parse_loop(an, duration);
                if (!we.data('has_fade_in_tween') && !we.data('has_flicker_tween')) {
                    pw.insert(
                        TweenMax.to(
                            we,
                            this.INIT_STYLE_TIME, {
                                css: {
                                    opacity: 1
                                },
                                ease: tween,
                            }
                        ),
                        //                    start_time
                        start_time + this.INIT_STYLE_TIME
                    );
                }
                pw.insert(
                    TweenMax.to(
                        wi, this.INIT_STYLE_TIME, {
                            rotationX: startRotateX,
                            rotationY: startRotateY,
                            rotationZ: startRotateZ,
                            transformOrigin: "center center",
                            ease: tween
                        }),
                    start_time
                );
                if (!loop.type) {
                    pw.insert(
                        TweenMax.to(
                            wi, duration, {
                                rotationX: endRotateX,
                                rotationY: endRotateY,
                                rotationZ: endRotateZ,
                                transformOrigin: "center center",
                                ease: tween,
                                onComplete: function() {
                                    wi.removeAttr('style');
                                }
                            }),
                        start_time + this.INIT_STYLE_TIME
                    );
                } else {
                    pw.insert(
                        TweenMax.to(
                            wi, loop.duration, {
                                rotationX: endRotateX,
                                rotationY: endRotateY,
                                rotationZ: endRotateZ,
                                transformOrigin: "center center",
                                repeat: loop.repeat,
                                yoyo: loop.yoyo,
                                ease: tween,
                                onComplete: function() {
                                    wi.removeAttr('style');
                                }
                            }),
                        start_time + this.INIT_STYLE_TIME
                    );
                }
                break;
                // 路径
            case an_type.PATH:
                if (an.points.length < 2) return;
                var loop = this.parse_loop(an, duration),
                    points = [],
                    dimensions = {
                        width: we.width(),
                        height: we.height()
                    };
                for (var i = 0; i < an.points.length; i++) {
                    var p = centerOffsetToBorderOffsetByEditorCanvas(an.points[i].x, an.points[i].y, dimensions);
                    points.push(p);
                };
                var init_style = {
                    transform: 'initial'
                };
                if (!we.data('has_fade_in_tween') && !we.data('has_flicker_tween')) {
                    pw.insert(
                        TweenMax.to(
                            we,
                            this.INIT_STYLE_TIME, {
                                css: {
                                    opacity: 1,
                                    transform: 'initial'
                                },
                                ease: tween,
                            }
                        ),
                        start_time + this.INIT_STYLE_TIME
                    );
                }
                if (!loop.type) {
                    pw.insert(
                        TweenMax.to(
                            we,
                            duration, {
                                bezier: {
                                    values: points,
                                    autoRotate: an.auto_rotate,
                                },
                                ease: tween,
                            }
                        ),
                        start_time + this.INIT_STYLE_TIME
                    );
                } else {
                    pw.insert(
                        TweenMax.to(
                            we,
                            loop.duration, {
                                bezier: {
                                    values: points,
                                    autoRotate: an.auto_rotate,
                                },
                                repeat: loop.repeat,
                                yoyo: loop.yoyo,
                                ease: tween,
                            }
                        ),
                        start_time + this.INIT_STYLE_TIME
                    );
                }
                break;
        }
    },
    getWidgetButtonByType: function(type) {
        var buttons =
            $.inArray(type, consts.STANDARD_BUTTON_TYPES) != -1 ? consts.STANDARD_BUTTONS :
            $.inArray(type, consts.FEATURE_BUTTON_TYPES) != -1 ? consts.FEATURE_BUTTONS :
            $.inArray(type, consts.YIXUN_GAMES_TYPES) != -1 ? consts.YIXUN_GAMES : consts.FIXED_BUTTONS;

        for (var i = 0, l = buttons.length; i < l; i++) {
            var oldItem = buttons[i];
            if (type == buttons[i].type) {
                var newItem = $.extend(true, {}, oldItem);
                return newItem;
            }
        }

        return null;
    },
    widgetIsEquals: function(oldWidget, newWidget) {
        var isEquals = true,
            propertyFields = consts.PROPERTY_FIELDS;
        for (var i = 0; i < propertyFields.length; i++) {
            var field = propertyFields[i];
            if (!angular.equals(oldWidget[field], newWidget[field])) {
                isEquals = false;
                break;
            }
        }
        return isEquals;
    },
    storage: function(key, value) {
        switch (arguments.length) {
            case 0:
                return '';
            case 1:
                try {
                    return JSON.parse(localStorage.getItem(key));
                } catch (err) {
                    localStorage.removeItem(key);
                }
                return '';
            case 2:
                if (value == null) {
                    localStorage.removeItem(key);
                    return '';
                } else {
                    return localStorage.setItem(key, JSON.stringify(value, null, ''));
                }
        }
        return '';
    },
    isBrightColor: function(hex) {
        var r = parseInt(hex.substr(0, 2), 16);
        var g = parseInt(hex.substr(2, 2), 16);
        var b = parseInt(hex.substr(4, 2), 16);
        var brightness = (r * 299 + g * 587 + b * 114) / 1000 / 255;
        return brightness > 0.5;
    },
    getSrcmByTypeAndBright: function(type, isBright, shareWay) {
        var rootPath = '/static/idealsee/images/new_editor/editor/',
            typeDesc = "",
            suffix = ".png";
        switch (parseInt(type)) {
            case consts.WIDGET_TYPE.CALLME:
                typeDesc = "dianhua";
                break;
            case consts.WIDGET_TYPE.APP_DOWNLOAD:
                typeDesc = "xiazai";
                break;
            case consts.WIDGET_TYPE.EXTEND:
                typeDesc = "tuozhan";
                break;
            case consts.WIDGET_TYPE.GEO:
                typeDesc = "daohang";
                break;
            case consts.WIDGET_TYPE.LINK:
                typeDesc = "lianjie";
                break;
            case consts.WIDGET_TYPE.MUSIC:
                typeDesc = "yiyue";
                break;
            case consts.WIDGET_TYPE.VIDEO_EXT:
                typeDesc = "shipin";
                break;
            case consts.WIDGET_TYPE.PAGE_JUMP:
                typeDesc = "page_jump";
                break;
            case consts.WIDGET_TYPE.TRIGGER:
                typeDesc = "wand";
                break;
            case consts.WIDGET_TYPE.CHANGE_ANIMATIONS:
                typeDesc = "run";
                break;
            case consts.WIDGET_TYPE.CHANGE_MATERIALS:
                typeDesc = "Shape";
                break;
            case consts.WIDGET_TYPE.FORM:
                typeDesc = "form";
                break;
            case consts.WIDGET_TYPE.NEARBY:
                typeDesc = "nearby";
                break;
            case consts.WIDGET_TYPE.SHARE:
                suffix = ".svg";
                rootPath = "/static/new_version/image/icon/";
                console.log(shareWay)
                switch(shareWay){
                    case 0: 
                        typeDesc = "icon_share_weixin";
                        break;
                    case 1:
                        typeDesc = "icon_share_friend";
                        break;
                    case 2:
                        typeDesc = "icon_share_weibo";
                        break;
                }
                return typeDesc ? (rootPath + typeDesc + (isBright ? "b" : "w") + suffix) : "";  
                break;
        }
        return typeDesc ? (rootPath + typeDesc + (isBright ? "1" : "") + suffix) : "";
    },
    getPaperCenter: function(rect) {
        return {
            width: rect.width / 2,
            height: rect.height / 2
        }
    },
    isEmptyObject: function(obj) {
        if (obj)
            for (var key in obj)
                return false;
        return true;
    },
    addExtraAttrs: function(widgets) {
        widgets.forEach(function(widget) {
            widget.uuid = widget.uuid || uuidHelper.generate();
        });
    },
    removeExtraAttrs: function(widgets) {
        var extraAttrs = consts.EXTRA_ATTRS;
        widgets.forEach(function(widget) {
            extraAttrs.forEach(function(attr) {
                if (attr in widget) {
                    delete widget[attr];
                }
            });
        });
        return widgets;
    },
    isString: function(obj) {
        return typeof obj === "string";
    },
    isArray: function(obj) {
        return (obj &&
            typeof obj === "object" &&
            obj.constructor &&
            obj.constructor === Array);
    },
    isObject: function(obj) {
        return (obj &&
            typeof obj === "object" &&
            !obj.constructor);
    },
    getEventObjByArray: function(args) {
        for (var i = 0, obj; obj = args[i++];) {
            if (typeof obj === "object" &&
                obj.type &&
                obj.type.indexOf("react") === -1 &&
                !(obj instanceof Event)) {
                return obj;
            }
        }
    },
    getItemByObjectDataOfType: function(data, type) {
        for (var key in data) {
            if (data.hasOwnProperty(key)) {
                var item = data[key];
                if (item instanceof type) {
                    return item;
                }
            }
        }
        return null;
    },
    isObjectEqual: function(a, b) {
        // require underscore.js
        return _.isEqual(a, b);
    },
    isArrayEqual: function(arrayA, arrayB) {
        var aLength = arrayA.length;
        var bLength = arrayB.length;

        if (aLength !== bLength) {
            return false;
        }

        for (var i = 0; i < aLength; i++) {
            if (!tool.isObjectEqual(arrayA[i], arrayB[i])) {
                return false;
            }
        }

        return true;
    },
    isSamePage: function(pageA, pageB) {
        return pageA.page_id === pageB.page_id;
    },
    getDifferentArrayData: function(arrayA, arrayB) {
        var largerArray = arrayA.length > arrayB.length ? arrayA : arrayB,
            smallerArray = arrayB.length > arrayA.length ? arrayA : arrayB;

        var result = [];
        for (var i = largerArray.length - 1, l = smallerArray.length - 1; i > l; i--) {
            result.push(largerArray[i]);
        }
        return result;
    },
    graphHelper: {
        initialize: function(paper) {
            this.paper = paper;
            return this;
        },
        defaultAttr: {
            'stroke': 'none'
        },
        drawEllipse: function(cx, cy, rx, ry, color) {
            this.paper.clear();
            this.graph = this.paper.ellipse(cx, cy, rx, ry);
            this.setAttr(color);
        },
        drawRectangle: function(x, y, w, h, color) {
            this.paper.clear();
            this.graph = this.paper.rect(x, y, w, h);
            this.setAttr(color);
        },
        setAttr: function(color) {
            this.graph.attr(this.defaultAttr);
            this.updateColor(color);
        },
        updatePageSize: function(w, h) {
            this.paper.setSize(w, h);
        },
        updateEllipseAttr: function(cx, cy, rx, ry) {
            this.updateAttr({
                cx: cx,
                cy: cy,
                rx: rx,
                ry: ry,
            });
        },
        updateRectangel: function(x, y, w, h) {
            this.updateAttr({
                x: x,
                y: y,
                width: w,
                height: h
            });
        },
        updateAttr: function(attr) {
            this.graph.attr(attr);
        },
        updateColor: function(color) {
            this.graph.attr('fill', '#' + color);
        },
        updateOpacity: function(opacity) {
            this.graph.attr('opacity', opacity);
        },
        updateRadius: function(radius) {
            this.graph.attr('r', radius);
        }
    },
    updateGShape: function(obj, gshape) {
        switch (gshape) {
            case 'circle':
                obj.graphHelp.drawEllipse(
                    obj.paperCenter.width,
                    obj.paperCenter.height,
                    obj.paperCenter.width,
                    obj.paperCenter.height,
                    obj.widget.color);
                break;
            case 'rectangle':
                obj.graphHelp.drawRectangle(
                    0,
                    0,
                    obj.widget.width,
                    obj.widget.height,
                    obj.widget.color);
                try {
                    obj.widget.radius = obj.widget.radius || 0;
                    var radius = parseInt(obj.widget.radius.replace('px', ''));
                } catch (ex) {}
                obj.graphHelp.updateRadius(radius);
                break;
            default:
                obj.graphHelp.drawEllipse(
                    obj.paperCenter.width,
                    obj.paperCenter.height,
                    obj.paperCenter.width,
                    obj.paperCenter.height,
                    obj.widget.color);
        }
    },
    updateFontSize: function(obj, ui) {
        obj.elements.widget.css({
            'font-size': this.getFontSizeByWidth(obj.elements.widget.height()) + 'px'
        });
    },
    workAroundBugInjQueryUI: function(obj, ui) {
        var min = consts.MIN_BUTTON_SIZE;
        if (ui.size.width < min || ui.size.height < min) {
            ui.size = obj._lastValidSize || ui.originalSize;
            ui.position = obj._lastValidposition || ui.originalPosition;
            ui.element.css(ui.size);
            ui.element.css(ui.position);
        } else {
            obj.status.lastValidSize = $.extend(true, {}, ui.size);
            obj.status.lastValidposition = $.extend(true, {}, ui.position);
        }
    },
    borderOffsetToCenterOffset: function(position, transform) {
        return {
            x: Math.round(position.left + position.width / 2 - transform.offset_x),
            y: Math.round(transform.offset_y - position.top - position.height / 2)
        };
    },
    centerOffsetToBorderOffset: function(obj, dimensions, offsets) {
        return {
            left: obj.transform.offset_x + offsets.x - dimensions.width / 2 - 0.5,
            top: obj.transform.offset_y - offsets.y - dimensions.height / 2
        }
    },
    getFontSizeByWidth: function(height) {
        height = height / 2;
        return height;
    },
    getPosition: function(widget, obj) {
        var width = widget.width,
            height = widget.height;
        var dimensions = {
                width: Math.max(width, consts.MIN_BUTTON_SIZE),
                height: Math.max(height, consts.MIN_BUTTON_SIZE)
            },
            coords = this.centerOffsetToBorderOffset(obj, dimensions, {
                x: parseInt(widget.offset_x) || 0,
                y: parseInt(widget.offset_y) || 0
            });
        if (widget.type == 19) { //浮屏按键不定位
            coords = {
                left: 0,
                top: 0
            }
        };
        return {
            left: Math.round(coords.left),
            top: Math.round(coords.top),
            width: Math.round(dimensions.width),
            height: Math.round(dimensions.height),
            zIndex: Math.round((widget.offset_z) * consts.Z_MAGNITUDE),
            fontSize: this.getFontSizeByWidth(dimensions.height)
        }
    },
    resize: function(width, height) {
        var res_picture_scale = window.is.CONST.res_picture_scale;
        var _width = width * res_picture_scale,
            _height = height * res_picture_scale;

        var scale = 1;
        if (_width > 1000) {
            scale = 1000 / _width;
            _width = 1000;
        }
        return {
            width: _width,
            height: _height * scale
        };
    },
    /**
     * 解析循环
     * @return {[type]} [description]
     */
    parse_loop: function(an, duration) {
        var loop = {},
            if_repeat = an.if_repeat,
            single_speed = parseFloat(an.single_speed) || 0.0,
            loop_type = parseInt(an.loop_type) || consts.LOOP_TYPE.NONE,
            repeat_count_type = parseInt(an.repeat_count_type || 0),
            repeat_count = parseInt(an.repeat_count) || 0;
        if_repeat = !!(single_speed > 0);

        if (if_repeat) {
            loop_type = consts.LOOP_TYPE.LOOP;
            repeat_count = duration / single_speed;
        }
        loop.yoyo = !!(loop_type == consts.LOOP_TYPE.PINGPONG)
        if (loop.yoyo) {
            repeat_count *= 2;
        }
        loop.type = loop_type;
        if (repeat_count == 0 || repeat_count_type == 0) {
            loop.repeat = -1;
            loop.duration = duration;
        } else {
            loop.repeat = repeat_count - 1;
            // 修改循环动效时间为单次循环时间
            loop.duration = duration;
        }
        return loop;
    },
    getWidgetsBySelectedIds: function(selectedIds, widgets) {
        var data = [].concat(widgets);

        data.forEach(function(widget) {
            widget.focus = $.inArray(widget.id, selectedIds) !== -1;
        });

        return data;
    },
    rebuildWidgetData: function(data, type, val) {
        var newData = {};
        newData[type] = val;
        if (type == 'light') {
            newData = {};
            newData.light = {};
            newData.light.intensity = val;
        }
        return $.extend(true, {}, data, newData);
    },
    rebuildWidget: function(data) {
        var widget = $.extend({}, data);
        if (widget.action && typeof widget.action.type !== "undefined") {
            widget.action.type = parseInt(widget.action.type);
        }
        return widget;
    },
    getRebulidWidget: function(widget, model) {
        if (!tool.isEmptyObject(model)) {
            widget.md5 = model.md5 || "";
            widget.action = widget.action || {};

            var type = widget.type;
            // 3d模型
            if (type === consts.WIDGET_TYPE.THREED) {
                //                if (model.md5_ios) widget.md5_ios = model.md5_ios;
                //                if (model.md5_android) widget.md5_android = model.md5_android;
                if (model.fbx_js_url) widget.action.fbx_js_url = model.fbx_js_url;
                if (model.html) widget.html = model.html;
            } else {
                var base = {
                    md5: model.md5 || "",
                    html: model.html || "",
                    url: model.url || ""
                };
                if (type === consts.WIDGET_TYPE.PICTURE || type === consts.WIDGET_TYPE.ALBUM) {
                    var width = widget.width ? widget.width : model.width,
                        height = widget.height ? widget.height : model.height,
                        resize = tool.resize(width, height);
                    widget.width = resize.width;
                    widget.height = resize.height;
                } else if (type === consts.WIDGET_TYPE.VIDEO) {
                    if (model.alpha_md5) {
                        widget.alpha_md5 = model.alpha_md5;
                    }
                }
                if (model.video_thumbnail) {
                    base["video_thumbnail"] = model.video_thumbnail;
                }
                if (!model.alpha_md5) widget.action = $.extend(true, widget.action, base);
                widget.html = model.html;
            }
        }
        return widget;
    },
    reBuildTypeDisplay: function(widget) {
        var oldTypeDisplay = widget.type_display,
            type_display,
            copy = oldTypeDisplay.split('copy');
        if (oldTypeDisplay.indexOf('copy') > -1) {
            var count = parseInt(copy[copy.length - 1]) || 0;
            count++;
            type_display = oldTypeDisplay.split('copy')[0] + 'copy' + count;

        } else type_display = oldTypeDisplay + 'copy';

        return type_display;
    },
    hasPropertyIn: function(source, dest, property) {
        for (var i = 0, item; item = dest[i++];) {
            if (typeof item[property] !== "undefined" && item[property] === source) {
                return true;
            }
        }
        return false;
    },
    initTimelines: function(timelines, triggers, dataProvider, widget) {
        var _timelines = $.extend({}, timelines);
        var __timeline = [];
        // 初始化重置 已被触发元件列表，已使用颜色列表
        var beTriggered = [];
        var beUsedColor = [];

        for (var widget_id in _timelines) {
            var ts = _timelines[widget_id],
                an_types = [],
                w = {};
            var wo = dataProvider.getSpecifyWidgetById(widget_id);

            // 已删除的元件不处理
            if (!wo) continue;

            // 已被触发元件
            if (wo.action && wo.action.trigger_widgets && wo.action.trigger_widgets.length) {
                [].push.apply(beTriggered, wo.action.trigger_widgets);
                // 已被使用颜色
                if (wo.action && wo.action.trigger_color) beUsedColor.push(wo.action.trigger_color);
            }

            // 无时间线不被触发
            if (!ts.length) continue;

            for (var i in ts) {
                var t = ts[i];
                an_types = an_types.concat(t.an_types);
            }
            // 无动效不被触发
            if (!an_types.length) continue;
            w.widget_id = widget_id;
            w.label = wo.label;
            w.icon_class = wo.icon_class;
            // 合成展示名称
            w.display = an_types.map(function(item) {
                return item.an_type_display
            }).join('|');
            if (triggers.indexOf(widget_id) > -1) w.selected = true;
            __timeline.push(w);
        }

        // 初始化当前元件的触发动效颜色
        var trigger_color = widget.action.trigger_widgets ?
            widget.action.trigger_color || this.getColor(beUsedColor) : this.getColor(beUsedColor);
        // 排除被其他元件触发的元件
        __timeline = __timeline.filter(function(item) {
            var widget_id = item.widget_id;
            // 本元件已选中的触发元件改变颜色
            if (triggers.indexOf(widget_id) > -1) {
                item.trigger_color = trigger_color;
                return true;
                // 非本元件选中的触发元件删除
            } else if (beTriggered.indexOf(widget_id) > -1) {
                return false;
                // 其他未被选中的元件置初始颜色
            } else {
                item.trigger_color = '#b5bbc7';
                return true;
            }
        });
        return [__timeline, trigger_color];
    },
    // 获取不重复的颜色
    getColor: function(beUsedColor) {
        var trigger_colors = ['#76BF5E', '#F8B537', "#DE5A1C", '#00ADDF', '#006885', '#AE66EE', '#E06271', '#FFEC00', '#39D1AF', '#417505'];
        for (var ix = 0; ix < trigger_colors.length; ix++) {
            if (beUsedColor.indexOf(trigger_colors[ix]) > -1) continue;
            return trigger_colors[ix];
        }
        return '#b5bbc7';
    },
    rebuildAnimationStyle: function(data, widget, centerOffsetToBorderOffsetByEditorCanvas) {
        // 动画类型
        var type = parseInt(data.an_type),
            direction = parseInt(data.direction),
            dimensions = {
                width: widget.width,
                height: widget.height
            };
        var rule = '';
        var an_type = consts.AN_TYPE;
        var start_value, end_value, custom = 0;
        var an_direction = consts.AN_DIRECTION;
        var widget_id = widget.id || widget.widget_id;
        switch (type) {
            case an_type.ERASE: // 擦出
                switch (direction) {
                    case an_direction.TOP_TO_BOTTOM:
                        rule = "@-webkit-keyframes h5EraseDown" + widget_id + "{0% {clip:rect(0," + dimensions.width + "px,0,0);}\n" +
                            "100%{clip:rect(0," + dimensions.width + "px," + dimensions.height + "px,0);}}";
                        break;
                    case an_direction.BOTTOM_TO_UP:
                        rule = "@-webkit-keyframes h5EraseUp" + widget_id + "{0% {clip:rect(" + dimensions.height + "px," + dimensions.width + "px," + dimensions.height + "px,0);}\n" +
                            "100%{clip:rect(0," + dimensions.width + "px," + dimensions.height + "px,0);}}";
                        break;
                    case an_direction.LEFT_TO_RIGHT:
                        rule = "@-webkit-keyframes h5EraseLeft" + widget_id + "{0% {clip:rect(0,0," + dimensions.height + "px,0);}\n" +
                            "100%{clip:rect(0," + dimensions.width + "px," + dimensions.height + "px,0);}}";
                        break;
                    case an_direction.RIGHT_TO_LEFT:
                        rule = "@-webkit-keyframes h5EraseRight" + widget_id + "{0% {clip:rect(0," + dimensions.width + "px," + dimensions.height + "px," + dimensions.width + "px);}\n" +
                            "100%{clip:rect(0," + dimensions.width + "px," + dimensions.height + "px,0);}}";
                        break;
                }
                break;
            case an_type.FLICKER: //透明度
                start_value = data.start_value,
                    end_value = data.end_value;

                if (start_value == 0 && end_value == 1) { //默认设置不重新修改css keyframes;
                    return false;
                }
                rule = "@-webkit-keyframes h5Ficker" + widget_id + "{0% {opacity: " + start_value + "}\n" +
                    "100%{opacity: " + end_value + "}}";
                break;
            case an_type.ZOOM: //缩放
                start_value = data.start_value,
                    end_value = data.end_value;

                if (start_value == 0 && end_value == 1) { //默认设置不重新修改css keyframes;
                    return false;
                }
                rule = "@-webkit-keyframes h5Zoom" + widget_id + "{0% {transform:scale(" + start_value + ");-webkit-transform:scale(" + start_value + ")}\n" +
                    "100%{transform:scale(" + end_value + ");-webkit-transform:scale(" + end_value + ")}}";
                break;
            case an_type.ROTATE: //旋转
                start_value = data.start_value,
                    end_value = data.end_value;
                if (start_value == 0 && end_value == 360) { //默认设置不重新修改css keyframes;
                    return false;
                }
                rule = "@-webkit-keyframes h5Rotate" + widget_id + "{0% {transform:rotate(" + start_value + "deg);-webkit-transform:rotate(" + start_value + "deg)}\n" +
                    "100%{transform:rotate(" + end_value + "deg);-webkit-transform:rotate(" + end_value + "deg)}}";
                break;
            case an_type.TRUN: //翻转
                var start_rotate_x = data.start_rotate_x || 0,
                    start_rotate_y = -data.start_rotate_y || 0,
                    end_rotate_x = data.end_rotate_x || 0,
                    end_rotate_y = -data.end_rotate_y || 0;
                if (!start_rotate_x && !start_rotate_y && !end_rotate_x && !end_rotate_y) {
                    return false;
                }
                rule = "@-webkit-keyframes h5Turn" + widget_id + "{0% {transform:rotateX(" + start_rotate_x + "deg) rotateY(" + start_rotate_y + "deg);-webkit-transform:rotateX(" + start_rotate_x + "deg) rotateY(" + start_rotate_y + "deg)}\n" +
                    "100%{transform:rotateX(" + end_rotate_x + "deg) rotateY(" + end_rotate_y + "deg);-webkit-transform:rotateX(" + end_rotate_x + "deg) rotateY(" + end_rotate_y + "deg);}}";
                break;
            case an_type.PATH: //路径
                if (data.points.length < 2) return;
                var points = [];
                var percent = 100 / data.points.length;
                var str = "";
                for (var i = 0; i < data.points.length; i++) {
                    var p = centerOffsetToBorderOffsetByEditorCanvas(data.points[i].x, data.points[i].y, dimensions);
                    points.push(p);
                };
                for (var i in points) {
                    var time = i * percent;
                    if (i == points.length - 1) time = 100;
                    str += '' + time + '%{transform:translate3d(' + points[i].left + 'px,' + points[i].top + 'px,0)}'
                }
                rule = "@-webkit-keyframes h5Path" + widget_id + "{" + str + "}";
                break;
            case an_type.ZOOM_MOVE: //缩放移动
                if (data.points.length < 2) return;
                var points = [];
                var percent = 100 / data.points.length;
                var str = "";
                for (var i = 0; i < data.points.length; i++) {
                    var p = centerOffsetToBorderOffsetByEditorCanvas(data.points[i].x, data.points[i].y, dimensions);
                    points.push(p);
                };
                for (var i in points) {
                    var time = i * percent;
                    if (i == points.length - 1) time = 100;
                    str += '' + time + '%{transform:translate3d(' + points[i].left + 'px,' + points[i].top + 'px,0) scale(' + i + ')}'
                }
                rule = "@-webkit-keyframes h5ZoomAndMove" + widget_id + "{" + str + "}";
                break;
            case an_type.FADE_IN_MOVE: //淡入移动
                if (data.points.length < 2) return;
                var points = [];
                var percent = 100 / data.points.length;
                var str = "";
                for (var i = 0; i < data.points.length; i++) {
                    var p = centerOffsetToBorderOffsetByEditorCanvas(data.points[i].x, data.points[i].y, dimensions);
                    points.push(p);
                };
                for (var i in points) {
                    var time = i * percent;
                    if (i == points.length - 1) time = 100;
                    str += '' + time + '%{transform:translate3d(' + points[i].left + 'px,' + points[i].top + 'px,0);opacity: ' + i + '}'
                }
                rule = "@-webkit-keyframes h5FadeAndMove" + widget_id + "{" + str + "}";
                break;
            case an_type.LIGHT_ERASE: //淡淡擦出
                switch (direction) {
                    case an_direction.TOP_TO_BOTTOM:
                        rule = "@-webkit-keyframes h5LightAndEraseDown" + widget_id + "{0% {clip:rect(0," + dimensions.width + "px,0,0);opacity: 0}\n" +
                            "100%{clip:rect(0," + dimensions.width + "px," + dimensions.height + "px,0);opacity: 1}}";
                        break;
                    case an_direction.BOTTOM_TO_UP:
                        rule = "@-webkit-keyframes h5LightAndEraseUp" + widget_id + "{0% {clip:rect(" + dimensions.height + "px," + dimensions.width + "px," + dimensions.height + "px,0);opacity: 0}\n" +
                            "100%{clip:rect(0," + dimensions.width + "px," + dimensions.height + "px,0);opacity: 1}}";
                        break;
                    case an_direction.LEFT_TO_RIGHT:
                        rule = "@-webkit-keyframes h5LightAndEraseLeft" + widget_id + "{0% {clip:rect(0,0," + dimensions.height + "px,0);opacity: 0}\n" +
                            "100%{clip:rect(0," + dimensions.width + "px," + dimensions.height + "px,0);opacity: 1}}";
                        break;
                    case an_direction.RIGHT_TO_LEFT:
                        rule = "@-webkit-keyframes h5LightAndEraseRight" + widget_id + "{0% {clip:rect(0," + dimensions.width + "px," + dimensions.height + "px," + dimensions.width + "px);opacity: 0}\n" +
                            "100%{clip:rect(0," + dimensions.width + "px," + dimensions.height + "px,0);opacity: 1}}";
                        break;
                }
                break;
        }
        this.stylesheet = document.styleSheets[document.styleSheets.length - 1];
        var rules = this.stylesheet.rules || [];
        var length = rules ? rules.length : 0;
        try {
            this.stylesheet.insertRule(rule, length);
        } catch (e) {

        }

    },
    rebuildAnimationParam: function(start_time, end_time, tween, an, widget, delay_time) {
        var start_time = parseFloat(start_time),
            end_time = parseFloat(end_time),
            delay_time = parseFloat(delay_time);
        var duration = end_time - start_time,
            delay_time = Math.abs(start_time - delay_time),
            tween = parseInt(tween),
            direction = parseInt(an.direction),
            animationName = 'h5FadeIn',
            end_value = an.end_value || 0,
            repeat = (an.loop_type > 0 ? an.repeat_count_type ? an.repeat_count : 'infinite' : 1) || 1;
        var an_type = consts.AN_TYPE;
        var an_direction = consts.AN_DIRECTION;
        var widget_id = widget.id || widget.widget_id;

        switch (tween) { //速度
            case 0:
                tween = 'linear';
                break;
            case 1:
                tween = 'ease-out';
                break;
            case 2:
                tween = 'ease-in';
                break;
        };
        var an_looptype = consts.AN_LOOPTYPE; //循环方式
        var ani_direct = 'normal';
        var loop_type = parseInt(an.loop_type);
        switch (loop_type) {
            case an_looptype.PINGPONG:
                ani_direct = 'alternate';
                break;
        }

        switch (an.an_type) {
            case an_type.FADE_IN: //淡入
                animationName = 'h5FadeIn';
                break;
            case an_type.FADE_OUT: //淡出
                animationName = 'h5FadeOut';
                break;
            case an_type.FLY_INTO: //飞入
                switch (direction) {
                    case an_direction.TOP_TO_BOTTOM:
                        animationName = "h5FlyInDown";
                        break;
                    case an_direction.BOTTOM_TO_UP:
                        animationName = "h5FlyInUp";
                        break;
                    case an_direction.LEFT_TO_RIGHT:
                        animationName = "h5FlyInLeft";
                        break;
                    case an_direction.RIGHT_TO_LEFT:
                        animationName = "h5FlyInRight";
                        break;
                }
                break;
            case an_type.ERASE: //擦出
                animationName = "h5Erase" + widget_id;
                switch (direction) {
                    case an_direction.TOP_TO_BOTTOM:
                        animationName = "h5EraseDown" + widget_id;
                        break;
                    case an_direction.BOTTOM_TO_UP:
                        animationName = "h5EraseUp" + widget_id;
                        break;
                    case an_direction.LEFT_TO_RIGHT:
                        animationName = "h5EraseLeft" + widget_id;
                        break;
                    case an_direction.RIGHT_TO_LEFT:
                        animationName = "h5EraseRight" + widget_id;
                        break;
                }
                break;
            case an_type.CUT: //切入
                animationName = "h5CutIn";
                switch (direction) {
                    case an_direction.TOP_TO_BOTTOM:
                        animationName = "h5CutInDown";
                        break;
                    case an_direction.BOTTOM_TO_UP:
                        animationName = "h5CutInUp";
                        break;
                    case an_direction.LEFT_TO_RIGHT:
                        animationName = "h5CutInLeft";
                        break;
                    case an_direction.RIGHT_TO_LEFT:
                        animationName = "h5CutInRight";
                        break;
                }
                break;
            case an_type.FLICKER: //透明度
                animationName = "h5Ficker" + widget_id;
                if (an.start_value == 0 && an.end_value == 1) {
                    animationName = "h5Ficker";
                }
                break;
            case an_type.BOUNCE: //弹跳
                switch (direction) {
                    case an_direction.TOP_TO_BOTTOM:
                        animationName = "bounceInDown";
                        break;
                    case an_direction.BOTTOM_TO_UP:
                        animationName = "bounceInUp";
                        break;
                    case an_direction.LEFT_TO_RIGHT:
                        animationName = "bounceInLeft";
                        break;
                    case an_direction.RIGHT_TO_LEFT:
                        animationName = "bounceInRight";
                        break;
                }
                break;
            case an_type.ZOOM: //缩放
                animationName = 'h5Zoom' + widget_id;
                if (an.start_value == 0 && an.end_value == 1) {
                    animationName = 'h5Zoom';
                }
                break;
            case an_type.TRUN: //翻转
                animationName = 'h5Turn' + widget_id;
                break;
            case an_type.ROTATE: //旋转
                animationName = 'h5Rotate' + widget_id;
                if (an.start_value == 0 && an.end_value == 360) {
                    animationName = 'h5Rotate';
                }
                break;
            case an_type.PATH:
                animationName = 'h5Path' + widget_id;
                break;
            case an_type.ZOOMOUT:
                animationName = 'h5ZoomOut';
                break;
            case an_type.ZOOM_MOVE:
                animationName = 'h5ZoomAndMove' + widget_id;
                break;
            case an_type.FADE_IN_MOVE:
                animationName = 'h5FadeAndMove' + widget_id;
                break;
            case an_type.ZOOM_ROTATE:
                animationName = 'h5ZoomAndRotate';
                break;
            case an_type.ROTATE_FLY_INTO:
                animationName = 'h5RotateAndFlyinto';
                switch (direction) {
                    case an_direction.TOP_TO_BOTTOM:
                        animationName = "h5RotateAndFlyintoDown";
                        break;
                    case an_direction.BOTTOM_TO_UP:
                        animationName = "h5RotateAndFlyintoUp";
                        break;
                    case an_direction.LEFT_TO_RIGHT:
                        animationName = "h5RotateAndFlyintoLeft";
                        break;
                    case an_direction.RIGHT_TO_LEFT:
                        animationName = "h5RotateAndFlyintoRight";
                        break;
                }
                break;
            case an_type.LIGHT_ERASE:
                animationName = "h5LightAndErase" + widget_id;
                switch (direction) {
                    case an_direction.TOP_TO_BOTTOM:
                        animationName = "h5LightAndEraseDown" + widget_id;
                        break;
                    case an_direction.BOTTOM_TO_UP:
                        animationName = "h5LightAndEraseUp" + widget_id;
                        break;
                    case an_direction.LEFT_TO_RIGHT:
                        animationName = "h5LightAndEraseLeft" + widget_id;
                        break;
                    case an_direction.RIGHT_TO_LEFT:
                        animationName = "h5LightAndEraseRight" + widget_id;
                        break;
                }
                break;
        }
        var str = '' + animationName + ' ' + duration + 's ' + delay_time + 's ' + repeat + ' ' + tween + ' forwards ' + ani_direct + '';
        return str;
    },
    checkWidgetType: function(id, dataProvider, timelines, callback) {
        if (!id) return consts.FOCUS_TABS.PAGE;

        var selectedWidget = dataProvider.getSpecifyWidgetById(id),
            action = selectedWidget.action,
            type = parseInt(action.type);

        callback = typeof callback === "function" ? callback : function() {};
        // redbag
        if (selectedWidget.type === consts.WIDGET_TYPE.REDBAG) {
            return consts.FOCUS_TABS.REDBAG;
        }
        if (selectedWidget.type === consts.WIDGET_TYPE.LOOKERS) {
            return consts.FOCUS_TABS.LOOKERS;
        }
        if (selectedWidget.type === consts.WIDGET_TYPE.APP_DOWNLOAD) {
            if (!action.iphone_url && !action.android_url) {
                callback();
                return consts.FOCUS_TABS.EVENT;
            }
        }
        if (selectedWidget.type === consts.WIDGET_TYPE.HOPEBANK) {
            return consts.FOCUS_TABS.HOPEBANK;
        }
        var expressions = {
            0: function() {
                return !action.number;
            },
            1: function() {
                return !action.url;
            },
            2: function() {
                return !action.target;
            },
            3: function() {
                return !action.content;
            },
            11: function() {
                for (var widget_id in timelines) {
                    var _timelines = timelines[widget_id];
                    for (var i in _timelines) {
                        var timeline = _timelines[i];
                        if (timeline.triggered_by && timeline.triggered_by.indexOf(selectedWidget.id) > -1) {
                            return false;
                        }
                    }
                }
                return true;
            },
            14: function() {
                return !action.md5 && !action.html;
            },
            15: function() {
                return !action.page_index;
            },
            17: function() {
                return !action.select_material;
            },
            18: function() {
                return action.select_animation == undefined;
            },
            21: function() {
                return !action.search_nearby;
            }
        };

        switch (type) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 11:
            case 14:
            case 15:
            case 17:
            case 18:
            case 21:
                if (expressions[type]()) {
                    callback();
                    return consts.FOCUS_TABS.EVENT;
                }
                break;
        }
        if (selectedWidget.type === consts.WIDGET_TYPE.FIXEDBTN) {
            return consts.FOCUS_TABS.FIXEDBTN;
        }
        return consts.FOCUS_TABS.PROPERTY;
    },
    converionColor: function(hex) {
        var step = 0.1;
        var r = parseInt(hex.substr(0, 2), 16);
        var g = parseInt(hex.substr(2, 2), 16);
        var b = parseInt(hex.substr(4, 2), 16);

        var hsb = this.RGB_2_HSB(r, g, b);

        hsb.B += .4;
        hsb.S -= .2;
        var rgb = this.HSB_2_RGB(hsb.H, hsb.S, hsb.B);

        rgb.R = parseInt(rgb.R > 255 ? 255 : rgb.R);
        rgb.G = parseInt(rgb.G > 255 ? 255 : rgb.G);
        rgb.B = parseInt(rgb.B > 255 ? 255 : rgb.B);

        return rgb;
    },
    RGB_2_HSB: function(R, G, B) {

        var var_Min = Math.min(Math.min(R, G), B);

        var var_Max = Math.max(Math.max(R, G), B);

        var hsb = { H: 0, S: 0, B: 0 };

        if (var_Min == var_Max) {

            hsb.H = 0;

        } else if (var_Max == R && G >= B) {

            hsb.H = 60 * ((G - B) / (var_Max - var_Min));

        } else if (var_Max == R && G < B) {

            hsb.H = 60 * ((G - B) / (var_Max - var_Min)) + 360;

        } else if (var_Max == G) {

            hsb.H = 60 * ((B - R) / (var_Max - var_Min)) + 120;

        } else if (var_Max == B) {

            hsb.H = 60 * ((R - G) / (var_Max - var_Min)) + 240;

        }

        if (var_Max == 0) {

            hsb.S = 0;

        } else {

            hsb.S = 1 - (var_Min / var_Max);

        }

        var var_R = (R / 255);

        var var_G = (G / 255);

        var var_B = (B / 255);

        hsb.B = Math.max(Math.max(var_R, var_G), var_B);

        hsb.H = (hsb.H >= 360) ? 0 : hsb.H;

        return hsb;

    },
    HSB_2_RGB: function(H, S, B) {

        var rgb = { R: 0, G: 0, B: 0 };
        var i, f, p, q, t;
        H = (H >= 360) ? 0 : H;

        if (S == 0) {

            rgb.R = B * 255;

            rgb.G = B * 255;

            rgb.B = B * 255;

        } else {

            i = Math.floor(H / 60) % 6;

            f = H / 60 - i;

            p = B * (1 - S);

            q = B * (1 - S * f);

            t = B * (1 - S * (1 - f));

            switch (i) {

                case 0:

                    rgb.R = B, rgb.G = t, rgb.B = p;

                    break;

                case 1:

                    rgb.R = q;
                    rgb.G = B;
                    rgb.B = p;

                    break;

                case 2:

                    rgb.R = p;
                    rgb.G = B;
                    rgb.B = t;

                    break;

                case 3:

                    rgb.R = p;
                    rgb.G = q;
                    rgb.B = B;

                    break;

                case 4:

                    rgb.R = t;
                    rgb.G = p;
                    rgb.B = B;

                    break;

                case 5:

                    rgb.R = B;
                    rgb.G = p;
                    rgb.B = q;

                    break;

            }

            rgb.R = rgb.R * 255;

            rgb.G = rgb.G * 255;

            rgb.B = rgb.B * 255;

        }

        return rgb;

    },
    RGB_TO: function(r, g, b) { //rgb转16进制
        var R = r.toString(16);
        if (R.length <= 1) {
            R = "0" + R;
        };
        var G = r.toString(16);
        if (G.length <= 1) {
            G = "0" + G;
        }
        var B = r.toString(16);
        if (B.length <= 1) {
            B = "0" + G;
        }
        return R + G + B;
    },
    // 补全url
    completionUrl: function(url) {
        var reg = /^((http|https):\/\/)([\s\S]*)$/;
        if (!reg.test(url)) {
            url = "http://" + url;
        }
        return url;
    },
    // 判断是否是小数
    isDecimal: function(number) {
        var result = /^-?(?:0|[1-9]\d*)(\.\d+)?$/.exec(number);
        return result && result[1];
    },
    sortBy: function(filed, rev, primer) { //按某个键值排序
        rev = (rev) ? -1 : 1;
        return function(a, b) {
            a = a[filed];
            b = b[filed];
            if (typeof(primer) != 'undefined') {
                a = primer(a);
                b = primer(b);
            }
            if (a < b) {
                return rev * -1;
            }
            if (a > b) {
                return rev * 1;
            }
            return 1;
        }
    },
    isWeiXin: function() {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
            return true;
        } else {
            return false;
        }
    },
    rebuildDelayTime: function(timelines, index, trigger_widget) {
        // 计算触发动效时动效延迟的时间
        var delay_time = 0;
        if (index > 0) {
            if (!trigger_widget) {
                return timelines[index - 1].end_time;
            }
            for (var i = index - 1; i >= 0; i--) {
                var timeline = timelines[i],
                    triggered_by = timeline.triggered_by || [];
                if (triggered_by.indexOf(trigger_widget) > -1) {
                    return timeline.end_time;
                }
            }
        }
        return delay_time;
    },
    changeUtcTime: function(datetime) {
        // 前端显示时间转换成后端存储格式
        var localDate = new Date(),
            localYear = localDate.getFullYear(),
            localMonth = localDate.getMonth() + 1;
        var timeStr = datetime.split(" "),
            date = timeStr[0].split("/"),
            time = timeStr[1].split(":"),
            year = parseInt(date[0]) < localYear || parseInt(date[0]) > 9999 ? localYear : parseInt(date[0]),
            hour = parseInt(time[0]) || 0,
            min = parseInt(time[1]) || 0,
            month = parseInt(date[1]),
            day = parseInt(date[2]);

        // 毫秒
        var targetTime = (new Date(year, month - 1, day, hour, min)).getTime();
        // 毫秒
        var offsetTime = localDate.getTimezoneOffset() * 60000;
        // 秒
        var endByDeadline = parseInt((targetTime + offsetTime) / 1000);

        return endByDeadline;
    },
    reBuildFormContent: function(widget) {
          const formTypeItems = {
              0: consts.BOOKINGFORMITEM,
              1: consts.JOBFORMITEM,
              2: consts.PRIZESFORMITEM,
              3: []
          };
          const type = parseInt(widget.form_type) || parseInt(widget.action.form_type);

          const form_items = {}, form_type_items = formTypeItems[type];
          consts.ALLFORMCONTENTITEM.forEach(function (item){
              if (form_type_items.includes(item.name)){
                  if(item.name =="phone"){
                      const param = {
                            name:'SMS',
                            required: 0,
                            value: $._("need sms verify")
                       }
                      item["SMS"] = param;
                  }
                  form_items[item.name] = item;
              }
          });

          widget.action.form_items = form_items;
          widget.action.reorder = form_type_items;

          return widget;
      },
    getSpecifyWidgetById(widgets,widget_id) {
        let result = widgets.filter(function (widget) {
            return widget.id === widget_id;
        });
        return result.length ? result[0] : null;
    },
    getTriggerColorByWidgetId: function(widgets,widget_id) {
        let widget = this.getSpecifyWidgetById(widgets,widget_id);
        if (widget) {
            if (widget.action && widget.action.trigger_color) {
                return widget.action.trigger_color;
            }
        }
    },
    getTriggerColorByTimeline: function(widgets,timeline) {
        let triggered_by = timeline.triggered_by || [];
        if (triggered_by.length) {
            return this.getTriggerColorByWidgetId(widgets,triggered_by[0]);
        }
    }
};

// module.exports = tool;
export default tool;
